package it.aekidna.xmlmapping
{
   import flash.events.EventDispatcher;
   import flash.events.IEventDispatcher;
   
   import mx.core.IFactory;

   [DefaultProperty("mappings")]
   [Event(name="beforePropertyMap", type="it.aekidna.xmlmapping.XmlMapPropertyEvent")]
   public class MapPropertyGroup extends EventDispatcher
   {
      public var mappings : Array;
      public var version : String = null;
      public var targetClass : IFactory = null;
      
      public function getProperties( inArray : Array = null ) : Array
      {
         if( inArray == null ) 
         {
            inArray = [];
         }         
         for each( var mapping : IEventDispatcher in mappings )
         {
            if( willTrigger( XmlMapPropertyEvent.BEFORE_PROPERTY_MAP ) &&  
               !mapping.willTrigger( XmlMapPropertyEvent.BEFORE_PROPERTY_MAP ) )
            {
               //group event handling is performed only if 
               //mapping child is not overriding event handling
               mapping.addEventListener( XmlMapPropertyEvent.BEFORE_PROPERTY_MAP, beforePropertyMapHandler );
            }
            if( mapping is MapPropertyGroup )
            {
               MapPropertyGroup( mapping ).getProperties( inArray );
            }
            else
            {
               if( version != null) {
                  MapProperty( mapping ).version = version;
               }
               if( targetClass != null ) {
                  MapProperty( mapping ).targetClass = targetClass;
               }
               inArray.push( mapping ); 
            }
         }
         return inArray;
      }
      
      private function beforePropertyMapHandler( event : XmlMapPropertyEvent ) : void
      {
         if( event.target != this )
         {
            var eventClone : XmlMapPropertyEvent = XmlMapPropertyEvent( event.clone() );
            dispatchEvent( eventClone );
            event.shouldMap = eventClone.shouldMap;
         } 
      }    
   }
}